<template>
  <div class="createPost-container">
    <div class="filter-container">
      <el-input v-model="listQuery.name" size="small" placeholder="输入模型名称" style="width: 200px;" class="filter-item"
        @keyup.enter.native="handleFilter" />
      <el-button class="filter-item" size="small" type="primary" icon="el-icon-search" @click="">搜索
      </el-button>
      <el-button class="filter-item" size="small" type="defalut" icon="el-icon-close" @click="" plain>清空</el-button>
    </div>
    <div class="btngroup">
      <el-button class="filter-item" size="mini" type="primary" icon="el-icon-plus" @click="newModel">新增</el-button>
      <el-button class="filter-item" size="mini" icon="el-icon-edit" @click="updaModel"
        :disabled="multipleSelection.length !== 1">修改</el-button>
      <el-button class="filter-item" size="mini" icon="el-icon-delete" @click="deleteModels"
        :disabled="multipleSelection.length == 0">删除</el-button>
      <el-button class="filter-item" size="mini" type="primary" icon="el-icon-upload" @click="deploymentModels"
        :disabled="multipleSelection.length !== 1">发布</el-button>
    </div>
    <div class="task-items">
      <el-table :data="modelList" stripe style="width: 100%;" size="small" v-loading="listLoading"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <!-- <el-table-column prop="id" label="编号" width="60"></el-table-column> -->
        <el-table-column prop="info.name" label="模型名称" min-width="280" align="left">
        </el-table-column>
        <el-table-column prop="info.description" label="模型描述" min-width="280" align="left">
        </el-table-column>
        <el-table-column prop="info.revision" label="版本" min-width="70">
        </el-table-column>
        <el-table-column label="创建日期" min-width="150">
          <template slot-scope="{row}">
            <span>{{ parseTime(row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="160">
          <template slot-scope="scope">
            <!--    <router-link :to="'http://106.52.194.219:8014/editor?modelId='+scope.row.ID_">-->
            <!--      <el-button type="text" size="small">查看</el-button>-->
            <!--    </router-link>-->
            <!--    <router-link :to="'http://106.52.194.219:8014/editor?modelId='+scope.row.ID_">-->
            <!--      <el-button type="text" size="small">编辑</el-button>-->
            <!--    </router-link>-->
            <el-button type="text" size="small" @click="updaModelById(scope.row.id)">查看</el-button>
            <el-button type="text" size="small" @click="updaModelById(scope.row.id)">编辑</el-button>
            <el-button type="text" size="small" @click="selectModelsUser(scope.row)">指派</el-button>
            <el-popover
            :ref="`popover-${scope.$index}`"
              placement="top"
              width="160">
              <p>这是一段内容这是一段内容确定删除吗？</p>
              <div style="text-align: right; margin: 0">
                <el-button size="mini" type="text" @click="cancelClick(scope)">取消</el-button>
                <el-button type="primary" size="mini" @click="deleteModelAndFush(scope)">确定</el-button>
              </div>
              <el-button type="text" size="small" slot="reference">删除</el-button>
            </el-popover>
            
            <!-- <el-button type="text" size="small" @click="deleteModelAndFush(scope.row.id)">删除</el-button> -->
          </template>
        </el-table-column>
      </el-table>
    </div>
     <!-- 打开人员安排窗口  -->
     <div class="">
        <el-dialog width="30%" title="部门指派" :visible.sync="dialogUserVisible">
          <el-radio-group v-model="departSelectType" style="margin-bottom: 10px">
              <el-radio :label="true">只选择父级</el-radio>
              <el-radio :label="false">包含子级</el-radio>
            </el-radio-group>
          <treeselect class="select" placeholder="请选择部门" v-model="departmentArr" multiple :options="departmentList" :normalizer="normalizer"/>
          <el-row type="flex" justify="center" style="margin-top:15px;">
            <el-button type="primary" size="small" @click="handAssignModels">保存</el-button>
          </el-row>
        </el-dialog>
      </div>
  </div>
</template>
<script>
  import { mapGetters } from 'vuex'
  import {
    getModels,
    createModel,
    deploymentModel,
    getAssignModelToDepart,
    getDepartByModelId,
    delModel
  } from '@/api/workflow.js'
  import {
    getUserDepartment
  } from '@/api/user.js'
  import { parseTime } from '@/utils/index.js'
  import axios from 'axios'
  import Cookies from 'js-cookie'
  import Treeselect from '@riophae/vue-treeselect'
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'
  export default {
    name: 'modelList',
    computed: {
      ...mapGetters([
          'id',
          'department'
        ])
    },
    components: {
      Treeselect
    },
    data() {
      return {
        modelList: [],
        modelId: null,
        listLoading: true,
        visible: false,
        listQuery: {
          page: 1,
          limit: 20,
          name: ''
        },
        departSelectType: true, // 模型管理部门多选类型
        modelObj: {}, // 模型对象信息
        multipleSelection: [],
        relateUsers: [], // 初始任务关联人员
        updateUsers: [], // 重新选择的人员
        dialogUserVisible: false,
        departmentList: [], // 部门列表数据
        departmentIds: [], // 部门ID列表数据
        departmentArr: [],
        normalizer(node) {
          return {
            id: node.id,
            label: node.dt_name,
            children: node.child,
          }
        },
      }
    },
    mounted() {
      this.getModelList()
      this.requestDepartments()
    },
    methods: {
      parseTime,
      // 获取所包含子级部门id
      getCascadeDepart(target, data, result) {
        data.forEach(item => {
          if(item.id == target){
            result.push(item.id)
            if (item.child && item.child.length > 0) {
              item.child.forEach(v =>{
                result.push(v.id)
              })
            }
          }else{
            if (item.child && item.child.length > 0) {
              this.getCascadeDepart(target, item.child, result);
            }
          }
        });
        return result;
      },
      // 指派模型给部门
      handAssignModels(){
        let departs = []
        if(this.departSelectType){
          // 只选择父级
          departs = this.departmentArr
        }else{
          // 父级 + 所包含子级部门id
          this.departmentArr.forEach(id =>{
            let result = this.getCascadeDepart(id, this.departmentList, [])
            departs = [...departs, ...result]
          })
        }
        const param = {
          groups: departs
        }
        getAssignModelToDepart(this.modelObj.id, param).then(res =>{
          if(res && res.data.code === '200'){
            this.dialogUserVisible = false
            this.$notify.success({
              title: '提示',
              message: '模型指派部门操作成功'
            })
          }
        })
      },
      // 请求部门信息
      requestDepartments() {
        getUserDepartment({owner: this.id }).then(res => {
          this.departmentList = res.data
          this.departmentIds = this.getDepartIds(res.data, [])
        })
      },
      // 获取所有部门id
      getDepartIds(data, result) {
        data.forEach(item => {
          // result = [...result, ...item.user_department]
            result.push(item.id);
          if (item.child && item.child.length > 0) {
            this.getDepartIds(item.child, result);
          }
        });
        return result;
      },
      // 选择模型关联人员
      selectModelsUser(row){
        this.modelObj = row
        getDepartByModelId(row.id).then(res =>{
          let data = res.data.data
          data = data.filter(e => e && e !== 'null' && this.departmentIds.includes(+e))
          this.departmentArr = data.map(e => +e)
      })
        this.dialogUserVisible = true
      },
      getModelList() {
        // 获取模型列表
        getModels().then(res => {
          const data = res.data.data
          data.forEach(
            e =>{
              e.info = JSON.parse(e.metaInfo)
            }
          )
          this.modelList = data

            this.listLoading = false
        })
      },

      updaModel() {
        if (this.multipleSelection.length != 0) {
          this.updaModelById(this.multipleSelection[0].ID_)
        }
      },

      updaModelById(id) {
        window.open(`${process.env.VUE_APP_WORKFLOW_URL}/modeler.html?modelId=` + id, '_slfe')
      },

      deploymentModels() {
        this.$confirm('此操作将发布模型, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.multipleSelection.forEach(item => {
            this.deploymentModelById({modelId: item.id, processName: item.info.name})
          })
        })
      },

      deploymentModelById(data) {
        deploymentModel(data).then(res => {
          this.$message({
            message: '发布成功！',
            type: 'success'
          });
        })
      },

      deleteModels() {
        this.$confirm('此操作将删除模型, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let queue = this.multipleSelection.map(item => {
                  return new Promise((resolve,reject) => {
                    this.deleteModelById(item.id)
                });
          });
          Promise.all(queue).then(result => {
              //执行后续操作
              this.$message.success('删除模型成功')
          }).catch(error => {
            this.$message.danger('删除模型失败')
          });
          // this.multipleSelection.forEach(item => {
          //   this.deleteModelById(item.id)
          // })
          this.getModelList()
        })
      },
      // 删除模型取消
      cancelClick(scope){ 
        scope._self.$refs[`popover-${scope.$index}`].doClose() 
      },
      deleteModelAndFush(scope) {
        scope._self.$refs[`popover-${scope.$index}`].doClose() 
        this.deleteModelById(scope.row.id)
      },

      // 提交删除任务
      deleteModelById(id) {
        delModel(id).then(res => {
          this.$message({
            message: '删除模型操作成功！',
            type: 'success'
          });
          this.getModelList()
        })
      },

      // 表格多选
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      handleFilter() {

      },
      newModel() {
        window.open(`${process.env.VUE_APP_WORKFLOW_URL}/activiti/create?depart= ` + this.department)
      }
    }
  }

</script>
<style lang="scss">
  .createPost-container {
    padding: 20px;

    .btngroup {
      margin-top: 16px;
    }

    .task-items {
      margin-top: 20px;
    }
    .el-button+.el-button {
      margin-left: 0;
    }
    .el-dialog__body{
      padding: 10px 20px;
    }
  }

</style>
